package com.yunhe.abnormal.controller.data;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.yunhe.abnormal.domain.data.AbnormalEvent;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.model.DomainList;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.model.ResultObject;
import com.yunhe.abnormal.service.data.AbnormalEventService;
import com.yunhe.common.util.QueryUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Api(value = "abnormalEvent",description = "异常事件维护", tags = {"Data_AbnormalEvent"})
@RestController
@RequestMapping("/abnormalEvents")
public class AbnormalEventController {
    @Autowired
    private AbnormalEventService abnormalEventService;

    @ApiOperation("新增事件")
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<ResultObject> post(@RequestBody AbnormalEvent event)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException, JsonProcessingException {
        AbnormalEvent result = abnormalEventService.create(event);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    /**
     * 批量新增事件
     * @param domainList 事件对象列表
     */
    @ApiOperation("批量新增事件")
    @RequestMapping(value = "/batch", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> batchPost(@RequestBody DomainList<AbnormalEvent> domainList)
            throws Exception {
        List<AbnormalEvent> eventList = domainList.getList();
        Iterable<AbnormalEvent> results = abnormalEventService.create(eventList);
        return new ResponseEntity<>(new ResultObject<>(results), HttpStatus.OK);
    }

    /**
     * 根据事件ID删除事件
     * @param id 事件ID
     */
    @ApiOperation("根据事件ID删除事件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "事件ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<ResultObject> delete(@PathVariable("id") Long id) {
        abnormalEventService.delete(id);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    @ApiOperation("根据事件ID获取事件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "事件ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<ResultObject> findById(@PathVariable("id") Long id) {
        AbnormalEvent result = abnormalEventService.findById(id);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    @ApiOperation("更新事件（更新指定字段）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "事件ID", required = true, dataType="long", paramType = "path"),
            @ApiImplicitParam(name = "stationId", value = "站点ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "devId", value = "设备ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "alarmId", value = "异常规则ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "userIdProcess", value = "处理人id", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "abnormalStatusId", value = "异常状态ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "alarmLevelId", value = "告警等级ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "userIdProcess", value = "处理人id", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "latestProcessTime", value = "处理时间，如“2017-12-06 00:00:00”", dataType = "date", paramType = "query")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
    public ResponseEntity<ResultObject> patch(@PathVariable("id") Long id,
                                              @RequestParam("stationId") Optional<Long> stationId,
                                              @RequestParam("devId") Optional<Long> devId,
                                              @RequestParam("alarmId") Optional<Long> abnormalRuleId,
                                              @RequestParam("userIdProcess") Optional<Long> userIdProcess,
                                              @RequestParam("abnormalStatusId") Optional<Long> abnormalStatusId,
                                              @RequestParam("alarmLevelId") Optional<Long> alarmLevelId,
                                              @RequestParam("latestProcessTime") Optional<String> latestProcessTime
    )
            throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        AbnormalEvent newEvent = abnormalEventService.update(id, stationId, devId, abnormalRuleId, userIdProcess, abnormalStatusId, alarmLevelId,
                latestProcessTime);
        return new ResponseEntity<>(new ResultObject<>(newEvent), HttpStatus.OK);
    }

    @ApiOperation("根据条件获得事件列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "stationIds", value = "电站ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "devId", value = "设备ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "alarmId", value = "异常名称", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "abnormalStatusIds", value = "异常状态", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "alarmLevelIds", value = "告警级别", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "dtime", value = "时间范围", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "queryStr", value = "查询条件", dataType = "string", paramType = "query")
    })
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<ResultObject> findByCondition(@RequestParam("stationIds") Optional<List<Long>> stationIds,
                                                        @RequestParam("devId") Optional<List<Long>> devId,
                                                        @RequestParam("alarmId") Optional<Long> abnormalRuleId,
                                                        @RequestParam("abnormalStatusIds") Optional<List<Long>> abnormalStatusIds,
                                                        @RequestParam("alarmLevelIds") Optional<List<Long>> alarmLevelIds,
                                                        @RequestParam("dtime") Optional<String> dtime,
                                                        @RequestParam("queryStr") Optional<String> queryStr,
                                                        @ModelAttribute PageParam pageParam) {
        Iterable<AbnormalEvent> results = abnormalEventService.retrieve(stationIds, devId, abnormalRuleId, abnormalStatusIds, alarmLevelIds, dtime,
                queryStr, pageParam);
        if (results instanceof Page) {
            Page<AbnormalEvent> pageContent = (Page<AbnormalEvent>) results;
            List<AbnormalEvent> content = pageContent.getContent();
            long totalElements = pageContent.getTotalElements();
            int totalPages = pageContent.getTotalPages();
            int page = QueryUtil.getPage(pageParam) + 1;
            int size = QueryUtil.getSize(pageParam);
            return new ResponseEntity<>(new ResultObject<>(content, page, size, totalElements, totalPages), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(new ResultObject<>(results), HttpStatus.OK);
        }
    }

    @ApiOperation("获取未消除事件对应表")
    @RequestMapping(value = "/readySet", method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getHistoryEventMap() {
        Map<String, List<AbnormalEvent>> readyEventMap = abnormalEventService.getHistoryEventMap();
        List<String> result = readyEventMap == null ? null : new ArrayList<>(readyEventMap.keySet());
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }
}
